use crate::gen_title;

pub fn ch4_5_1() {
    gen_title("ch4_5_1", 18);

    let b = foo("world");
    println!("{}", b);

    fn foo(x: &str) -> String {
        let a = "hello, ".to_string() + x;
        a
    }
}

pub fn ch4_5_2() {
    gen_title("ch4_5_2", 18);

    let a = Box::new(3);

    println!("{}", a);
}

pub fn ch4_5_3() {
    gen_title("ch4_5_3", 18);

    let arr = [0; 1000];
    let arr1 = arr;

    println!("{:?}", arr.len());
    println!("{:?}", arr1.len());

    let arr = Box::new([0; 1000]);
    let arr1 = arr;
    println!("{:?}", arr1.len());
}

pub fn ch4_5_4() {
    gen_title("ch4_5_4", 18);

    #[derive(Debug)]
    enum List {
        Cons(i32, Box<List>),
        Nil,
    }

    let list = List::Cons(1, Box::from(List::Cons(2, Box::from(List::Nil))));

    println!("{:?}", list);
}

pub fn ch4_5_5() {
    gen_title("ch4_5_5", 18);

    trait Draw {
        fn draw(&self);
    }

    #[derive(Debug)]
    struct Button {
        id: u32,
    }

    impl Draw for Button {
        fn draw(&self) {
            println!("这是屏幕上第{}号按钮", self.id);
        }
    }

    #[derive(Debug)]
    struct Select {
        id: u32,
    }

    impl Draw for Select {
        fn draw(&self) {
            println!("这是屏幕上第{}号选择框", self.id);
        }
    }

    let elems: Vec<Box<dyn Draw>> = vec![Box::new(Button { id: 1 }), Box::new(Select { id: 2 })];

    for e in elems {
        e.draw();
    }
}

pub fn ch4_5_6() {
    gen_title("ch4_5_6", 18);

    let arr = vec![Box::new(1), Box::new(2)];
    let [first, second, ..] = &arr[..] else {
        return;
    };
    let sum = **first + **second;
    println!("{}", sum);
}

pub fn ch4_5_7() {
    gen_title("ch4_5_7", 18);

    let s = gen_static_str();
    println!("{}", s);

    fn gen_static_str() -> &'static str {
        let mut s = String::new();
        s.push_str("hello, world");

        Box::leak(s.into_boxed_str())
    }
}
